#! /usr/bin/perl -w

use strict;
use IO::Socket;
use XML::Simple;
use Carp;

use constant DEFAULT_PORT => 4000;
#define socket
my $port = shift || SIMPLE_TCP_PORT;

my $sock_obj = IO::Socket::INET->new(
    LocalPort => $port,
    Proto     => 'tcp',
    Reuse     => 1,
    Listen    => SOMAXCONN
) or die "oo_tcp_s3: could not create socket object: $!\n";

warn "Server listening on port: ", $sock_obj->sockport, ".\n";
#

#listen on the port
while ( my $client_obj = $sock_obj->accept ) {
    my $secs = 10;

    ##	Function Read message;
    print $client_obj "Sleeping for $secs seconds ... \n";
    sleep($secs);
    print $client_obj "I awake, only to die ... \n";

    ##$client_obj->close
    ##       or warn "oo_tcp_s3: close failed: $!\n";
}
$sock_obj->close;
#
sub linux_release_node {
    if ( @_ > 1 ) { carp "Only can have one input, not @_."; }
    my $cpu_needed = shift;
    if ( $cpu_needed > 0 ) 
	{
        	##assuming each node have 4 cores, and round up to a integer.
        	my $nodes_release = ( ($cpu_needed) / 4 );
        	for ( ; $nodes_release > 0 ; $nodes_release-- ) 
		{
        		##cout << nodes_release << " submit a release job\n" << endl;
			system("/opt/dualboot/release_1_node.job");
			sleep(1);
		}
	}
	return 0;
	}

sub LinuxAwakeJob
{
	if (@_>1){carp "Only can have one input, not @_.";}
	my $laststuck = shift;
	if ($laststuck =~ /'none'/)
		{
			return 1;
		}
	my $cmd="sudo qrun $laststuck";
	system($cmd);
	return 0;
}

sub process_win_message
{
	if (@_>1){carp "Only can have one input, not @_."}
	my $win_message= shift;
	my %win_info=(status          => substr($win_message,0,1),
		      required_node   => substr($win_message,1,3),
		      jobfirstqueuing => substr($win_message,5,36));
	##cout << “Client Job:\n” << in_job.cpu_needed << endl;d
	##write requirement into out_job
	out_job.cpu_needed = LinuxRequire(out_job.laststuckjobid,out_job.stuckjobid);
	LinuxAwakeJob(out_job.laststuckjobid);
	## release nodes only when Linux are not stuck.
	if (out_job.cpu_needed <= 0)
	{
		LinuxReleasenode(in_job.cpu_needed);
	}
	
	##send(c, &out_job, sizeof(struct job), 0);
}






